const express = require("express");
const router = new express.Router();
// const db = require("../db/db_link")
const Users = require("../modles/users_schema")

const user_name_reg = /^[A-Za-z][A-Za-z0-9_]{4,19}$/;
const password_reg = /^[A-Za-z0-9.]{8,15}$/;

router.post("/register", async (req, res) => {
    console.log(req.body)
    if (user_name_reg.test(req.body.user_name) && password_reg.test(req.body.password)) {
        try {
            await Users.create(req.body);
            res.send("注册成功")
        } catch (err) {
            console.log(err)
            console.log("数据存储失败")
            res.send("请重新输入")
        }
    } else {
        console.log("用户名或密码格式错误")
        res.send("用户名或密码格式错误")
    }
})

router.post("/login", async (req, res) => {
    console.log(req.body)
    const {
        user_name,
        password
    } = req.body;
    if (user_name_reg.test(req.body.user_name) && password_reg.test(req.body.password)) {
        try {
            let this_user = await Users.findOne({
                user_name
            })
            if (user_name == this_user.user_name && password == this_user.password) {
                console.log("验证通过")
                res.send("验证通过")
            } else {
                console.log("用户名或密码错误")
                res.send("用户名或密码错误")
            }
            // res.send("成功")
        } catch (err) {
            console.log(err)
            console.log("登陆失败-用户名或密码错误")
            res.send("用户名或密码错误")
        }
    } else {
        console.log("用户名或密码格式错误")
        res.send("用户名或密码错误")
    }
})


module.exports = router;